package org.btik.lightweb.paser;

import org.btik.light.meta.event.cmd.DefaultCmd;
import org.btik.light.meta.exception.LightException;
import org.btik.light.meta.base.CmdCode;
import org.btik.light.meta.base.Command;
import org.springframework.boot.json.GsonJsonParser;

import java.util.ArrayList;
import java.util.Map;
/**
 * @author lustre
 * @version 1.0
 * @since 2021/5/15 12:37
 * web命令的解析器
 */
public class WebCmdParser implements CmdCode {

    public static Command parse(String msg) {
        GsonJsonParser parser = new GsonJsonParser();
        Map<String, Object> stringObjectMap = parser.parseMap(msg);
        Object snO = stringObjectMap.get(DEV_SN);
        String sn;
        if (snO instanceof String) {
            sn = (String) snO;
        }else {
            throw new LightException("DEV_SN is required");
        }
        DefaultCmd webCmd = new DefaultCmd();
        webCmd.setTarget(sn);
        Object op = stringObjectMap.get(OP_CODE);
        int opCode;
        if (op == null) {
            throw new LightException("OP_CODE is required");
        } else {
            if (op instanceof Double) {
                opCode = ((Double) op).intValue();
            } else {
                String opChar = String.valueOf(op);
                opCode = opChar.charAt(0) - '0';
            }
        }
        webCmd.setOpcode(opCode);
        Object o = stringObjectMap.get(PRAMS);
        webCmd.setParams((ArrayList<?>) o);
        return webCmd;
    }

}
